using Avalonia.Controls;
using Avalonia.Input;
using DesktopApp.ViewModels;
using System.Threading.Tasks;
using Avalonia;

namespace DesktopApp.Views.Controls
{
    public partial class RuleItemView : UserControl
    {
        // Drag state variables
        private Point _startPoint;
        private bool _isDragging = false;

        public RuleItemView()
        {
            InitializeComponent();
        }

        private void RuleItem_PointerPressed(object? sender, PointerPressedEventArgs e)
        {
            // Only start drag on left mouse button press over the handle (or whole item for now)
            if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
            {
                _startPoint = e.GetPosition(null); // Position relative to the top-level window
                _isDragging = true; // Set flag, actual drag starts on PointerMoved
                System.Diagnostics.Debug.WriteLine($"PointerPressed on Rule: {((RuleItemViewModel?)DataContext)?.Name}");
            }
        }

         private async void RuleItem_PointerMoved(object? sender, PointerEventArgs e)
         {
            if (!_isDragging) return;

            Point currentPoint = e.GetPosition(null);
            // Check if mouse moved significantly to differentiate click from drag
            if (System.Math.Abs(currentPoint.X - _startPoint.X) > 3 || System.Math.Abs(currentPoint.Y - _startPoint.Y) > 3)
            {
                 if (DataContext is RuleItemViewModel vm)
                 {
                    System.Diagnostics.Debug.WriteLine($"Starting Drag for Rule: {vm.Name}");
                    var dataObject = new DataObject();
                    // Store the ViewModel itself for easy access on drop
                    dataObject.Set(RuleItemDragFormat, vm);

                    // Reset dragging flag before starting DoDragDrop
                    _isDragging = false;

                    // Start the drag operation
                    var effect = await DragDrop.DoDragDrop(e, dataObject, DragDropEffects.Move);
                    System.Diagnostics.Debug.WriteLine($"DragDrop completed with effect: {effect}");
                }
                else
                {
                    _isDragging = false; // Reset if DataContext is wrong
                }
            }
         }

        private void RuleItem_PointerReleased(object? sender, PointerReleasedEventArgs e)
        {
             _isDragging = false; // Reset dragging flag on release
             System.Diagnostics.Debug.WriteLine("PointerReleased on Rule.");
        }

        // Define a unique format string for our dragged data
        public static readonly string RuleItemDragFormat = "application/vnd.logclear.ruleitemviewmodel";
    }
} 